<?php
/**
 * AuthController.php.
 *
 * @author: cnx7 <zysafe@live.cn> 2021-03-15
 */

namespace app\controllers;

use common\domain\base\ApiBaseController;
use common\domain\components\AccessToken;
use common\domain\helper\Request;
use common\models\BkAdmin;
use Yii;
use yii\db\ActiveRecord;

class AuthController extends ApiBaseController
{
    public function behaviors(): array
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator']['optional'] = ['login'];

        return $behaviors;
    }

    /**
     * 管理员登录
     *
     * @throws \yii\base\Exception
     */
    public function actionLogin(): array
    {
        $username = Request::getRequest('username');
        $password = Request::getRequest('password');

        /** @var ActiveRecord $user */
        $user = BkAdmin::findOne(['username' => $username]);

        if (!$user || !password_verify($password, $user->password)) {
            return $this->responseError('登录失败，用户名或密码错误');
        }

        $user->last_login_at = time();
        $user->last_login_ip = Yii::$app->request->userIP;
        $user->save();

        $ssid = AccessToken::createSession($user);

        return $this->responseSuccess(['access_token' => $ssid]);
    }

    /**
     * 注销
     */
    public function actionLogout(): array
    {
        $token = AccessToken::getRequestAccessToken();

        if ($token) {
            AccessToken::clearSession($token);
        }

        return $this->responseSuccess();
    }
}
